<!DOCTYPE html>
<html>
<head>
    <!--<title>集群系统监控巡检报告</title>-->
    <title>{{.Project}}</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .card {
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-top: 15px;
        }
        .stat-item {
            text-align: center;
        }
        .stat-item .label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }
        .stat-item .value {
            font-size: 1.2em;
            font-weight: bold;
        }
        .stat-item .value.alert {
            color: #dc3545;
        }
        .stat-item .value .critical {
            color: #dc3545;
            margin-right: 10px;
        }
        .stat-item .value .warning {
            color: #ffc107;
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            table-layout: auto;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
            min-width: 100px;
        }

        /* 指标名称列 */
        th:first-child, td:first-child {
            min-width: 150px;
        }

        /* 检测时间列 */
        th:last-child, td:last-child {
            min-width: 180px;
        }

        /* 状态列 */
        th:nth-last-child(2), td:nth-last-child(2) {
            min-width: 80px;
        }

        /* 值列 */
        th:nth-last-child(3), td:nth-last-child(3) {
            min-width: 100px;
        }

        th {
            background-color: #4CAF50;
            color: white;
        }

        /* 表格行状态样式 */
        tr.warning { 
            background-color: #fff3cd !important;
        }
        tr.normal { 
            background-color: #d4edda !important;
        }
        tr.critical { 
            background-color: #f8d7da !important;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .label-value {
            display: inline-block;
            background-color: #e9ecef;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.9em;
            word-break: break-all;
            white-space: normal;
        }

        h1, h2, h3 {
            color: #333;
        }
        .section {
            margin-bottom: 30px;
        }
        .chart-container {
            height: 400px;
            margin-bottom: 30px;
        }

        /* 响应式支持 */
        @media screen and (max-width: 1200px) {
            .container {
                padding: 10px;
            }
            
            table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            td, th {
                white-space: nowrap;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!--<h1>集群系统监控巡检报告</h1>-->
        <h1 style="text-align: center">{{.Project}}</h1>
        <p>生成时间: {{.Timestamp.Format "2006-01-02 15:04:05"}}</p>

        <!-- 概览卡片 -->
        <div class="summary-cards">
            {{range $type, $group := .MetricGroups}}
            <div class="card {{$type}}">
                <h3>{{$type}}</h3>
                <div class="stats">
                    <div class="stat-item">
                        <div class="label">最大值</div>
                        <div class="value">{{printf "%.2f" $group.Stats.MaxValue}}</div>
                    </div>
                    <div class="stat-item">
                        <div class="label">最小值</div>
                        <div class="value">{{printf "%.2f" $group.Stats.MinValue}}</div>
                    </div>
                    <!-- <div class="stat-item">
                        <div class="label">平均值</div>
                        <div class="value">{{printf "%.2f" $group.Stats.Average}}</div>
                    </div> -->
                    <div class="stat-item">
                        <div class="label">告警数</div>
                        <div class="value {{if gt $group.Stats.AlertCount 0}}alert{{end}}">
                            {{$group.Stats.AlertCount}}/{{$group.Stats.TotalCount}}
                        </div>
                    </div>
                    <div class="stat-item">
                        <div class="label">告警详情</div>
                        <div class="value">
                            <span class="critical">严重:{{$group.Stats.CriticalCount}}</span>
                            <span class="warning">警告:{{$group.Stats.WarningCount}}</span>
                        </div>
                    </div>
                </div>
            </div>
            {{end}}
        </div>

        <!-- 图表部分 -->
        <div class="section">
            <h2>资源使用概览</h2>
            <div class="chart-container">
                <canvas id="resourceChart"></canvas>
            </div>
        </div>

        <!-- 详细指标表格 -->
        {{range $type, $group := .MetricGroups}}
        <div class="section">
            <h2>{{$type}} 监控指标</h2>
            {{range $metricName, $metrics := $group.MetricsByName}}
            <h3><li>{{$metricName}}</li></h3>
	    {{if eq (len $metrics) 0 }}
             <p>未查询到数据</p>
            {{end}}
            {{if gt (len $metrics) 0}}
            <table>
                <tr>
                    <th>指标名称</th>
                    {{$headerLabels := (index $metrics 0).Labels}}
                    {{range $headerLabels}}
                        <th data-label-name="{{.Name}}">{{.Alias}}</th>
                    {{end}}
                    <th>值</th>
                    <th>状态</th>
                    <th>检测时间</th>
                </tr>
                {{range $metric := $metrics}}
                <tr class="{{.Status}}">
                    <td>{{.Name}}</td>
                    {{range $headerLabels}}
                        {{$labelName := .Name}}
                        {{range $metricLabel := $metric.Labels}}
                            {{if eq $metricLabel.Name $labelName}}
                                <td data-label-name="{{$labelName}}">
                                    <span class="label-value">{{$metricLabel.Value}}</span>
                                </td>
                            {{end}}
                        {{end}}
                    {{end}}
                    <td>{{printf "%.2f" $metric.Value}}{{$metric.Unit}}</td>
                    <td>
                        {{if eq .Status "normal"}}正常
                        {{else if eq .Status "warning"}}警告
                        {{else if eq .Status "critical"}}严重
                        {{else}}{{.Status}}
                        {{end}}
                    </td>
                    <td>{{.Timestamp.Format "2006-01-02 15:04:05"}}</td>
                </tr>
                {{end}}
            </table>
            {{end}}
            {{end}}
        </div>
        {{end}}
    </div>

<script>
    // 生成随机颜色
    function getRandomColor() {
        const hue = Math.random() * 360;
        return {
            background: `hsla(${hue}, 70%, 95%, 1)`,
            border: `hsla(${hue}, 70%, 70%, 1)`
        };
    }

    // 设置卡片样式
    document.addEventListener('DOMContentLoaded', function() {
        const cards = document.querySelectorAll('.card');
        const cardCount = cards.length;
        
        // 根据卡片数量优化布局
        const container = document.querySelector('.summary-cards');
        if (cardCount <= 2) {
            container.style.gridTemplateColumns = `repeat(${cardCount}, 1fr)`;
        } else if (cardCount <= 4) {
            container.style.gridTemplateColumns = 'repeat(2, 1fr)';
        }

        // 为每个卡片设置随机颜色
        cards.forEach(card => {
            const colors = getRandomColor();
            card.style.backgroundColor = colors.background;
            card.style.borderLeft = `4px solid ${colors.border}`;
        });
    });

    // 初始化图表
    const ctx = document.getElementById('resourceChart').getContext('2d');
    const data = {{.MetricGroups}}
    const labels = []; 
    const datasets = [];

    // 添加通用的数据获取函数
    function getMetricValues(metricName, filterFn = null) {
        const values = [];
        const labels = new Set(); // 使用 Set 存储唯一的标签
        
        for (const [type, group] of Object.entries(data)) {
            if (group.MetricsByName && group.MetricsByName[metricName]) {
                for (const metric of group.MetricsByName[metricName]) {
                    if (filterFn && !filterFn(metric)) continue;
                    
                    // 获取实例标签
                    const instanceLabel = metric.Labels.find(label => 
                        label.Name === "instance" || label.Name === "node"
                    );
                    if (instanceLabel) {
                        labels.add(instanceLabel.Value.split(':')[0]);
                        values.push(parseFloat(metric.Value));
                    }
                }
            }
        }
        return { values, labels: Array.from(labels) };
    }

    // 获取各项指标数据
    const cpuData = getMetricValues('CPU使用率');
    const memoryData = getMetricValues('内存使用率');
    const diskData = getMetricValues('磁盘使用率', (metric) => {
        return metric.Labels.some(label => 
            label.Value === "rootfs" || label.Value === "/"
        );
    });

    // 使用第一个指标的标签作为图表标签
    const chartLabels = cpuData.labels;
    // 添加颜色判断函数
    function getColorByValue(value) {
        if (value >= 90) return '#dc3545';  // 红色告警 (>=90%)
        if (value >= 80) return '#ffc107';  // 黄色告警 (80-90%)
        return '#4CAF50';                   // 绿色正常 (<80%)
    }
    // 创建数据集
    const chartDatasets = [
        {
            label: 'CPU使用率',
            data: cpuData.values,
            backgroundColor: cpuData.values.map(value => getColorByValue(value)),
        },
        {
            label: '内存使用率',
            data: memoryData.values,
            backgroundColor: memoryData.values.map(value => getColorByValue(value)),
        },
        {
            label: '磁盘使用率',
            data: diskData.values,
            backgroundColor: diskData.values.map(value => getColorByValue(value)),
        }
    ];

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: chartLabels,
            datasets: chartDatasets, 
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: '资源使用情况'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            }
        }
    });
</script>
</body>
</html>